<template>
  <div class="wrap">
    <div class="ani-con" :class="ani" v-show="showYanhua">
    </div>
    <div class="tip01 tipsp" @click="onBack"> <span>参会名单</span> <img src="../../static/img2/icon02.png" alt=""></div>
    <!-- <div class="logo-box-r">
      <div class="item01"><img src="../../static/img2/shansong_logo.png" alt=""></div>
    </div> -->
    <div class="left">
      <!-- <div class="box-bg-bottom"><img src="../../static/img2/lottory05.png" alt=""></div> -->
      <div class="box-bg-border01"><img src="../../static/img2/lottory03.png" alt=""></div>
      <div class="left-logo-con">
        <img class="left-logo" src="../../static/img2/lottory04.png" alt="">
        <div class="people-num">参与人数 <span class="num">{{count}}</span> 人</div>
      </div>
      <el-row class="option">
        <el-col :span="24" class="people">
          <span>&nbsp;&nbsp;&nbsp;&nbsp;待抽取</span>
          <input type="text" class="num" value=InNum v-model="InNum" @change="pnChange(num)" readonly>
          <span>人</span>
        </el-col>
        <el-col :span="24" class="jiangxiang">
          <span>选择奖项</span>
          <el-select class="jiangxiang-el-select" v-model="prize" size="small" placeholder="---"
                     @change="onPrizeChange">
            <el-option v-for="item in prizeList" :key="item.id" :label="item.name" :value="item">
            </el-option>
          </el-select>
          <span style="opacity: 0;">奖</span>

        </el-col>
      </el-row>
      <div class="btnBox">
        <div class="choujiang-btn choujiang-btn02" :class="{'disable': btnState === 2}" @click="onLottery"
             v-if="showChoujiang">{{btnLabel[btnState]}}
        </div>
        <div class="choujiang-btn choujiang-btn02 disable" v-else>抽奖中..</div>
      </div>



      <!-- 抽奖选项 -->

    </div>

    <!-- 中奖列表 -->
    <div class="right-content">
      <img src="../../static/img2/lottory02.png" class="right-title" alt="">
      <div class="right" ref="rightBox">
        <div class="no-people" v-if="currentItem.length ==0">
          <p>暂无幸运嘉宾哦,请点击左侧的抽奖按钮进行抽取吧</p>
        </div>
        <UserItem v-for="(item, index) in currentItem" :key="index" :item="item" class="ss" @delete="deleteOne(item.user_id,index)"
                  :class=" {
                    user01:inPool.length<3,
                    user02:inPool.length<=6&&inPool.length>=3,
                    user03:inPool.length>6
                    }"></UserItem>
      </div>
    </div>

  </div>
</template>

<script>
  import api from '@/api';
  import * as m_types from '@/store/mutation-types';
  import UserItem from './UserItemSp';

  export default {
    data() {
      return {
        // 签到人数
        sign: 0,
        list: [],
        lotteryList: [],
        // 已经中奖的人员列表，为了实现抽奖动画的人员去重
        lotteryResult: {},
        uniqueList: [],
        currentItem: new Array(),
        num: 0,
        lottoryNum:70,  // 一页显示的人数
        prize: null,
        prizeList: [],
        btnState: 0,
        speed: 70,
        // btnType: ['primary', 'plain'],
        btnLabel: ['开始抽奖', '停止', '开始抽奖'],

        // 抽奖结果，延迟到点击"停止"时处理
        resultData: null,
        pn2Text: '当前奖项',
        clearTimer: null,
        timerNum: 0,
        timerList: [],
        showChoujiang: true,
        lotteryNum: 0,
        inPool: [],
        count: 0,
        in: 0,
        inLottoryMan: null,
        cancelResult:true,
        isDelete:false, //是否删除过人
        InNum:0, //当前奖项的人数,并且抽奖后会删除相应的人

        ani: '',
        showYanhua: false,
        YanhuaTimer: null
      };
    },
    mounted() {
      let data = this.$store.state.app.data;
      if (!data) {
        this.$router.push({path: '/home'});
        return;
      }
      this.$root.$on('lottory',this.onLottery)
      this.$root.$on('setPrize',this.onPrizeChange)
      this.$root.$on('deleteOne',this.deleteOne)
      this.sign = data.sign;
      this.list = data.list;
      //     this.currentItem = this.list[(this.list.length * Math.random()) >> 0]

      // 获取到初始未抽奖的数组
      this.newCurrentItem(this.num);

      // 获取奖项
      api.getPrize({}).then(data => {
        if (data.code) {
          this.$message(data.message);
          return;
        }
        data = data.data;
        this.count = data.count;
        this.prizeList = data.list;
        this.prizeList.forEach(o => {
          o.added = 0;
        });
      });
      api.getLotteryResult({}).then(data => {
        // console.log(data);
        if (data.code) {
          this.$message(data.message);
          return;
        }
        const list = data.data.list;
        list.forEach(a => {
          a.list.forEach(person => {
            const id = person.user_id || person.id;
            this.lotteryResult[id] = person;
          });
        });
      });
      this.getYanhuaPath()
    },
    beforeDestroy() {
      this.$root.$off('lottory')
      this.$root.$off('setPrize')
      this.$root.$off('deleteOne')
      clearInterval(this.clearTimer);
      clearInterval(this.YanhuaTimer)
    },
    methods: {
      numChange(value) {
        if (!value) {
          setTimeout(() => {
            this.num = 1;
          }, 0);
        }
      },
      async onLottery() {
        var that = this;

        if (this.btnState === 2) {
          return;
        }
        if (this.btnState === 1) {
          this.btnState = 2;
          let data = this.resultData;
          console.log(data);
          if (!data) {
            //停止定时器并且赋值
            // 此时会在最坏的情况下，采用前端随机抽奖
            this.lottorySet();
            return;
          }
          this.lotteryList = data.data.list;
          // 如果报错,则直接清除定时器
          if (data.code) {
            this.$confirm(data.message, {
              showClose: false,
              center: true
            });
            this.btnState = 0;
            this.timerNum = 0;
            this.cancelResult=true
            this.clearAll();
            return;
          }

          //停止定时器并且赋值
          this.lottorySet();
          this.$root.$emit('sendMsg', 'syncLotteryResult');
        }
        else {
          if (!this.count) {
            this.$confirm('人数不足！', {
              showClose: false,
              center: true
            });
            this.cancelResult=true
            return;
          }
          if (this.prize === null) {
            this.$confirm('请选择奖项！', {
              showClose: false,
              center: true
            });
            this.cancelResult=true
            return;
          }
          this.btnState = 1;
          this.lotteryList = [];
          this.cancelResult=false
          // 是否显示抽奖按钮
          this.showChoujiang = false;

          let per ;
          this.prizeList.forEach((d)=>{
            if(d.id == this.prize.id){
                per = d.per
            }
          })
          // 取目前奖项和所有人的最小值
          this.inLottoryMan = Math.min(this.prize.count, this.count);
          if(per === 0){

          }else{
            this.inLottoryMan = Math.min(per,this.inLottoryMan)
          }

          await api
          .getLottery({
            prize_id: this.prize.value,
            num: this.num,
            activity_id:window.activity_id,
            per:per
          })
          .then(data => {
            this.resultData = data;
            this.showChoujiang = true;
            console.log(this.resultData.data.list,'获奖人员名单');
            this.$root.$emit('sendMsg', 'lottoryResult',this.resultData.data.list);
          });
          if (this.resultData.code) {
            this.$confirm(this.resultData.message, {
              showClose: false,
              center: true
            });
            this.clearAll();
            this.btnState = 2;
            this.cancelResult=true
            return;
          }
          console.log(this.resultData.data.list.length,'人员总数')
          this.inLottoryMan = this.resultData.data.list.length

          // this.inLottoryMan = Math.min(this.prize.count, this.count,this.inLottoryMan);
          // this.inLottoryMan > this.lottoryNum && (this.inLottoryMan = this.lottoryNum);
          // 新建动画数组，防止修改原数组内容
          this.timerList = JSON.parse(JSON.stringify(this.list)).slice(0, this.inLottoryMan);
          this.newCurrentItem(this.inLottoryMan);
          this.AllsetInterval(this.inLottoryMan);

          // 抽取完带抽取人数减少相应人数
          this.InNum != '---' && (this.InNum -= this.resultData.data.list.length)
        }
      },
      deleteOne(id,index) {
        if(id instanceof Object){
          let obj = id
          api.deleteOneMan({
            activity_id:window.activity_id,
            user_id:obj.id
          }).then((data)=>{
            this.currentItem.splice(obj.index,1)
            this.prize.count += 1
          this.InNum != '---' && (this.InNum += 1)
            this.isDelete = true
          })
          return;
        }
         this.$confirm('确定删除此人吗', {
          showClose: false,
          center: true
        }).then(()=>{
            api.deleteOneMan({
            activity_id:window.activity_id,
            user_id:id
          }).then((data)=>{
            this.currentItem.splice(index,1)
            this.prize.count += 1
            this.isDelete = true
            this.InNum != '---' && (this.InNum += 1)
          })
        })

      },
      onPrizeChange(item) {
        this.isDelete = false
        this.pn2Text = item.name;
        this.btnState = 0;
        this.prize = item
        console.log(this.prize);
        if (item.num) {
          this.num = item.num;
          this.inLottoryMan = item.num;
          
        this.InNum = item.num
        }
      },
      newCurrentItem(num) {
        this.inPool = [];
        this.currentItem = [];
        for (let i = 0; i < num; i++) {
          this.inPool.push(this.list[(this.list.length * Math.random()) >> 0]);
        }
      },
      onBack() {
        this.$router.back();
      },
      lottorySet() {
        let n = 0;
        this.clearTimer = setInterval(() => {
          if (this.timerList[this.timerNum]) {
            var listTimer = this.timerList[this.timerNum]['timerId'];
            clearInterval(this.timerList[this.timerNum]['timerId']);
            if (this.timerNum < this.lotteryList.length) {
              const person = this.lotteryList[this.timerNum];
              this.lotteryResult[person.user_id] = person;
              this.$set(
                this.currentItem,
                this.timerNum,
                person
              );
            }
            else {
              // warning!!!
              // 此处应该永远不被执行到，这是在网络挂掉的情况下，在最坏的情况下，采取下下策的前端随机抽奖
              // 确保在人数不足的情况下，即使有多人中奖，也不会出现bug
              let person = this.uniqueList[0];
              for (const p of this.uniqueList) {
                if (!this.lotteryResult[p.user_id]) {
                  this.lotteryResult[p.user_id] = p;
                  person = p;
                  this.$set(
                    this.currentItem,
                    this.timerNum,
                    person
                  );
                  break;
                }
              }
            }
            // this.currentItem[this.timerNum] = this.lotteryList[this.timerNum];
            // this.$forceUpdate();
            this.timerNum = this.timerNum + 1;
          }
          else {
            clearInterval(this.clearTimer);
            console.log('全部清除完毕', this.inLottoryMan);
            this.btnState = 0;
            this.timerNum = 0;
            this.cancelResult=true
            this.prize.added += this.inLottoryMan;
            this.prize.count -= this.inLottoryMan;
            this.count -= this.inLottoryMan;

            this.showYanhua = true
            setTimeout(() => {
              this.showYanhua = false
            }, 2000)
          }
        }, 300);
      },
      clearAll() {
        clearInterval(this.clearTimer);
        this.timerList.forEach(o => {
          clearInterval(o.timerId);
        });
        return;
        this.clearTimer = setInterval(() => {
          if (this.timerList[this.timerNum]) {
            var listTimer = this.timerList[this.timerNum]['timerId'];
            clearInterval(this.timerList[this.timerNum]['timerId']);
            this.timerNum = this.timerNum + 1;
            console.log('ok clear');
          }
          else {
            clearInterval(this.clearTimer);
            this.timerNum = 0;
          }
        }, 0);
      },
      AllsetInterval(num) {
        const arr = [];
        for (const p of this.list) {
          if (!this.lotteryResult[p.user_id]) {
            arr.push(p);
          }
        }
        this.uniqueList = arr;
        for (let i = 0; i < num; i++) {
          this.timerList[i]['timerId'] = setInterval(() => {
            this.currentItem[i] =
              this.uniqueList[(this.uniqueList.length * Math.random()) >> 0];
            this.$forceUpdate();
          }, this.speed);
        }
      },
      getYanhuaPath() {
        let i = 1
        this.YanhuaTimer = setInterval(() => {
          if (i == 51) {
            i = 1
          }
          this.ani = `an${i}`
          i++
        }, 100)
      }
    },
    components: {
      UserItem
    }
  };
</script>
<style scoped>
  @import "../../static/css/lottery.css";
  @import "../../static/css/ani.css";
</style>

<style>

  .user01{
    width:35%!important;
    padding: 2%!important;
    padding-bottom: 3%!important;
  }
  .user01 img{
    margin:40px 0!important;
  }
  .user02{
    width:20%!important;
    margin-bottom:20px;
  }


  .user03{
    width:14%!important;
    margin-bottom:10px;
  }
  .user03 img{
    margin:0!important;
  }

  .user03 .name-text{
    font-size:18px!important;
  }
  .user03 .zhiwei-text{
    font-size:11px!important
  }
  /* .user04{
    width:12.5%!important;

  } */
  .jiangxiang-el-select {
    border-radius: 5px;
    /* background: #f0cc8b; */
    width: 45%;
    margin: 0 4px;
  }

  .jiangxiang-el-select .el-input__inner::-webkit-input-placeholder {
    color: #fff;
  }

  .jiangxiang-el-select .el-input__inner {
    padding: 0 !important;
    text-align: center !important;
    background: url('../../static/img2/img07.png');
    background-size: contain;
    background-position: center;
    background-repeat: no-repeat;
    border: none;
    color: #fff;
    /* font-size: 24px; */
    font-size:20px;
    font-weight: bold;
    height: 40px !important;
    line-height: 40px !important;
  }

  .jiangxiang-el-select .el-input__suffix {
    display: none;
  }

  .right-title{
    position:absolute;
    top: 0;
    left:50%;
    transform:translate(-50%,-50%) scale(0.8);
    width:auto!important
  }
</style>
